package com.jsbb.service.common;

import com.jsbb.config.ParamsConfig;
import com.jsbb.util.IdUtils;
import com.jsbb.vo.common.FileVo;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件Service
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private ParamsConfig paramsConfig;

    public FileVo upload(MultipartFile file) throws Exception {
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = IdUtils.getId() + suffix;
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(paramsConfig.getMinioBucket())
                        .object(fileName)
                        .stream(file.getInputStream(), -1, 10485760)
                        .contentType(file.getContentType())
                        .build());
        FileVo fileVo = new FileVo();
        fileVo.setUrl(paramsConfig.getMinioEndpoint() + "/" + paramsConfig.getMinioBucket() + "/" + objectWriteResponse.object());
        return fileVo;
    }
}
